package com.toutoushidao.ssm.util;

import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoDatabase;

import java.util.Arrays;

public class MongoHelper {

//    static final String SERVER_ADDRESS = "127.0.0.1";// 本机访问
//    static final int PORT = 27017;
//    static final String DBName = "parrot-dapp";
//    //    static final String SERVER_ADDRESS = "39.98.237.58";// 外网访问
//    static final String LOGIN_NAME = "PixelBird";
//    static final String LOGIN_PWD = "UGP0oY!JnM";

    static final String SERVER_ADDRESS = "127.0.0.1";// 本机访问
    static final int PORT = 27017;
    static final String DBName = "parrot-dapp";
    //    static final String SERVER_ADDRESS = "39.98.237.58";// 外网访问
//    static final String LOGIN_NAME = "PixelBird";
//    static final String LOGIN_PWD = "UGP0oY!JnM";

    public MongoHelper() {
    }

    public MongoClient getMongoClient() {
        MongoClient mongoClient = null;
        try {
            // 连接到 mongodb 服务
            System.out.println("Connect to mongodb successfully");
//            MongoCredential lstCredentials = MongoCredential.createCredential(LOGIN_NAME, DBName, LOGIN_PWD.toCharArray());
            mongoClient = new MongoClient(new ServerAddress(SERVER_ADDRESS, PORT));//, Arrays.asList(lstCredentials));
        } catch (Exception e) {
            System.err.println(e.getClass().getName() + ": " + e.getMessage());
        }
        return mongoClient;
    }

    public MongoDatabase getMongoDataBase(MongoClient mongoClient) {
        MongoDatabase mongoDataBase = null;
        try {
            if (mongoClient != null) {
                // 连接到数据库
                mongoDataBase = mongoClient.getDatabase(DBName);
                System.out.println("Connect to DataBase successfully");
            } else {
                throw new RuntimeException("MongoClient不能够为空");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mongoDataBase;
    }

    public void closeMongoClient(MongoDatabase mongoDataBase, MongoClient mongoClient) {
        if (mongoDataBase != null) {
            mongoDataBase = null;
        }
        if (mongoClient != null) {
            mongoClient.close();
        }
        System.out.println("CloseMongoClient successfully");
    }
}
